package handler

import (
	"context"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"soul/api/request"
	"soul/global"
	"soul/inter/dao"
	"soul/inter/model"
	"soul/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	var req request.Login
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.Users
	dao.GetOneByFields(&model.Users{}, &user)
	if user.Account == req.Account {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "此账号已存在",
			"data": nil,
		})
		return
	}
	get := global.Rbd.Get(context.Background(), "sendSms"+req.Account+"register")
	if req.SendSms != get.Val() {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "短信验证码错误",
			"data": nil,
		})
		return
	}
	user = model.Users{
		Account:  req.Account,
		PassWord: req.Password,
	}
	if !dao.Create(&user) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "登录成功",
		"data": user,
	})
}

func SendSms(c *gin.Context) {
	var req request.SendSms
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	code := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(req.Account, strconv.Itoa(code))
	if err != nil {
		return
	}
	if *sms.Body.Code != "OK" {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  *sms.Body.Message,
			"data": err.Error(),
		})
		return
	}
	set := global.Rbd.Set(context.Background(), "sendSms"+req.Account+req.Source, code, time.Minute*5)
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": set,
	})
}
